from django.core.validators import FileExtensionValidator
from rest_framework import serializers
from django.contrib.auth import get_user_model

OAUser = get_user_model()


class staffSerializer(serializers.Serializer):
    # 字段校验
    realname = serializers.CharField(max_length=20,error_messages={"required": "请输入用户名！"})
    email = serializers.EmailField(error_messages={"required": "请输入邮箱！",'invalid':'请输入正确格式的邮箱！'})
    password = serializers.CharField(max_length=20,error_messages={"required":'请输入密码'})

    '''
    attrs 是一个 dict 他包含了所有字段的 已经通过类型转换和字段级验证的数据
    即将被用来创建或者更新 模型实例的 干净数据 (clean data)
    '''
    def validate(self,attrs):
        request = self.context.get('request')
        print(f"序列化中的 request.data : {request.data}")
        email = attrs.get('email')
        ##1、验证邮箱
        if OAUser.objects.filter(email=email).exists():
            raise serializers.ValidationError("该用户已存在，请勿重复添加")
        ##2、验证是否是leader 只有 leader 才可以创建
        if request.user.department.leader.uid != request.user.uid:
            raise serializers.ValidationError("只有 部门 leader 才能添加")
        return  attrs

## 激活验证的 序列化
class ActiveStaffSerializer(serializers.Serializer):
    email = serializers.EmailField(error_messages={"required": "请输入邮箱",'invalid':'请输入正确的格式'})
    password = serializers.CharField(max_length=20,error_messages={"required": '请输入密码！'})

    def validate(self,attrs):
        email = attrs.get('email')
        password = attrs.get('password')
        user = OAUser.objects.filter(email=email).first()
        print(f"user is {user}")
        if not user or not user.check_password(password):
            raise serializers.ValidationError("邮箱或者密码错误")
        attrs['user'] = user
        return attrs


###上传 excel 的 序列化
class StaffUploadSeriazlizer(serializers.Serializer):
    file = serializers.FileField(
        validators=[FileExtensionValidator(['xlsx','xls'])],
        error_messages={'required':'请上传文件！'}
    )